package com.littlebee.storychild.common.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.text.TextUtils;

import com.littlebee.storychild.common.BaseApplication;

import java.util.List;
import java.util.Stack;

/**
 * 作者：liaoyong on 2016/7/8 10:03
 * 邮箱：liaoyong@tuliu.com
 * 描述：Activity栈管理工具类
 */
public class AppManager {

	private static Stack<Activity> activityStack;
	private static AppManager instance;

	private AppManager() {
	}

	/**
	 * 单一实例
	 */
	public static AppManager getAppManager() {
		if (instance == null) {
			instance = new AppManager();
		}
		return instance;
	}

	public Stack<Activity> getAll() {
		return activityStack;
	}

	/**
	 * 按照下标查找压入栈内的Activity实例
	 *
	 * @param index
	 * @return
	 */
	public Activity findActivityByIndex(int index) {
		if (index < 0) {
			return null;
		}
		if (activityStack != null && activityStack.size() - 1 >= index) {
			return activityStack.get(index);
		} else {
			return null;
		}
	}

	/**
	 * 添加Activity到堆栈
	 */
	public void addActivity(Activity activity) {
		if (activityStack == null) {
			activityStack = new Stack<Activity>();
		}
		activityStack.add(activity);
	}

	/**
	 * 获取当前Activity（堆栈中最后一个压入的）
	 */
	private Activity currentActivity() {
		Activity activity = activityStack.lastElement();
		return activity;
	}

	public String getRunningActivityName() {
		if (activityStack == null || activityStack.size() == 0) {
			return "";
		}
		String contextString = currentActivity().toString();
		return contextString.substring(contextString.lastIndexOf(".") + 1, contextString.indexOf("@"));
	}

	/**
	 * 结束当前Activity（堆栈中最后一个压入的，也就是我们在APP中现在所看到的）
	 */
	public void finishActivity() {
		Activity activity = activityStack.lastElement();
		finishActivity(activity);
	}

	/**
	 * 结束指定的Activity
	 */
	public void finishActivity(Activity activity) {
		if (activity != null) {
			activityStack.remove(activity);
			if (!activity.isFinishing()) {
				activity.finish();
			}
		}
	}

	/**
	 * 当Activity被调用onDestory时从堆栈中去除
	 *
	 * @param activity
	 */
	public void removeActivity(Activity activity) {
		if (activity != null) {
			activityStack.remove(activity);
		}
	}

	/**
	 * 结束指定类名的Activity
	 */
	public void finishActivity(Class<?> cls) {
		Stack<Activity> tempActivityStack = new Stack<Activity>();
		for (int i = (activityStack.size() - 1); i >= 0; i--) {
			if (activityStack.get(i).getClass().equals(cls)) {
				tempActivityStack.add(activityStack.get(i));
				break;
			}
		}
		if (!tempActivityStack.isEmpty()) {
			finishActivity(tempActivityStack.get(0));
		}
	}

	/**
	 * 结束所有Activity
	 */
	public void finishAllActivity() {
		if (activityStack != null && !activityStack.isEmpty()){
			for (int i = (activityStack.size() - 1); i >= 0; i--) {
				//栈内不为空，并没有在Activity栈中被销毁
				if (activityStack.get(i) != null && !activityStack.get(i).isFinishing()) {
					activityStack.get(i).finish();
				}
			}
			activityStack.clear();
		}
	}

	/**
	 * 结束所有Activity除了指定Activity外
	 */
	public void finishAllActivityWithoutSpeciality(Class<?> cls) {
		Stack<Activity> tempActivityStack = new Stack<Activity>();
		for (int i = (activityStack.size() - 1); i >= 0; i--) {
			//首先是要真是存在于Activity栈中的实例
			if (activityStack.get(i) != null && !activityStack.get(i).isFinishing()) {
				//不同的，销毁
				if (!activityStack.get(i).getClass().equals(cls)) {
					activityStack.get(i).finish();
				}
				//相同的，保留
				else {
					tempActivityStack.add(activityStack.get(i));
				}
			}
		}
		activityStack.clear();
		activityStack.addAll(tempActivityStack);
	}

	/**
	 * 结束所有Activity除了指定Activity外
	 */
	public void finishAllActivityWithoutThis() {
		Activity act = activityStack.lastElement();
		for (int i = (activityStack.size() - 1); i >= 0; i--) {
			if (activityStack.get(i) != null) {
				if (!act.equals(activityStack.get(i)) && !activityStack.get(i).isFinishing()) {
					activityStack.get(i).finish();
				}
			}
		}
		activityStack.clear();
		activityStack.add(act);
	}


	/**
	 * 判断第index位置的Activity实例是不是cls类型的Activity
	 *
	 * @param cls
	 * @param index
	 * @return
	 */
	public boolean isSpecialityActivity(int index, Class<?> cls) {
		boolean isActivity = false;
		if (index < 0 || activityStack.isEmpty() || index > (activityStack.size() - 1)) {
			return isActivity;
		}
		if (activityStack.get(index).getClass().equals(cls)) {
			isActivity = true;
		}
		return isActivity;
	}

	public boolean isForeground(Context context, String className) {
		if (context == null || TextUtils.isEmpty(className)) {
			return false;
		}

		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
		if (list != null && list.size() > 0) {
			ComponentName cpn = list.get(0).topActivity;
			if (className.equals(cpn.getClassName())) {
				return true;
			}
		}

		return false;
	}

	/**
	 * 找出对应Activity实例在堆栈中的位置
	 *
	 * @param cls
	 * @return
	 */
	public int localeActivity(Class<?> cls) {
		int activityIndex = -1;
		if (activityStack == null || activityStack.isEmpty()) {
			return activityIndex;
		}
		for (int i = 0; i < activityStack.size(); i++) {
			if (activityStack.get(i).getClass().equals(cls)) {
				activityIndex = i;
				break;
			}
		}
		return activityIndex;
	}

	/**
	 * 退出应用程序
	 */
	public void AppExit() {
		try {
			finishAllActivity();
			ActivityManager activityMgr = (ActivityManager) BaseApplication.getInstance()
					.getSystemService(Context.ACTIVITY_SERVICE);
			activityMgr.killBackgroundProcesses(DeviceUtil.getAppPackageName());
			android.os.Process.killProcess(android.os.Process.myPid());
			System.exit(0);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
